package com.jpress.control;

import java.util.Calendar;
import java.util.List;

import com.jpress.dao.DAOAdmin;
import com.jpress.dao.DAOBlog;
import com.jpress.dao.DAOCategoria;
import com.jpress.dao.DAOPost;
import com.jpress.model.Post;

public class PostControl {
		DAOPost daoPost = new DAOPost();
		DAOBlog daoBlog = new DAOBlog();
		DAOAdmin daoAdmin = new DAOAdmin();
		DAOCategoria daoCategoria = new DAOCategoria();
	public int getPostQtde() {
		return (int) this.daoPost.findAll().size();
	}

	public boolean cadastrarPost(Post novoPost, int idAdmin, int idBlog) {
		try {
			novoPost.setData(Calendar.getInstance());
			novoPost.setBlog(daoBlog.findById(idBlog));
			novoPost.setAutor(daoAdmin.findById(idAdmin));
			this.daoPost.begin();
			this.daoPost.persist((Post) novoPost);
			this.daoPost.commit();
			return true;
		} catch (Exception e) {
			return false;
		} finally{
			this.daoPost.close();
		}
	}

	public List<Post> meusPosts(int id) {
		String query = "SELECT p FROM Post p WHERE p.autor.id = '" + String.valueOf(id) + "' ORDER BY p.data DESC";
		return this.daoPost.findAllWithMaxWithQuery(query, 5);
	}

	public Post getPostById(int id) {
			return this.daoPost.findById(id);
	}

	public boolean excluirPost(Post post) {
		try {
			this.daoPost.begin();
			this.daoPost.remove(post);
			this.daoPost.commit();
			return true;
		} catch (Exception e) {
			return false;
		} finally{
			this.daoBlog.close();
		}
		
	}

	public boolean atualizarPost(Post postAtual) {
		try {
			this.daoPost.begin();
			this.daoPost.merge(postAtual);
			this.daoPost.commit();
			return true;
		} catch (Exception e) {
			return false;
		}finally{
			this.daoPost.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Post> getPostsByBlogId(int id) {
		String query = "SELECT p FROM Post p WHERE p.blog.id = '" + String.valueOf(id) + "' ";
		return this.daoPost.findAllByQuery(query);
	}

}
